<template>
  <el-form-item :class="getClz(['upload-img','autoheight',...classNames])" :label="opt.text" :prop="opt.name" v-if="!opt.hide" size="mini">
    <el-upload
      class="upload-demo" :accept="opt.props.accept" :disabled="opt.loading || opt.props.disabled"
      action="="
      :multiple="opt.multiple"
      :limit="opt.limit"
      :on-exceed="handleExceed"
      :show-file-list="opt.showFile"
      :file-list="fileList"
      :http-request="upload"
      list-type="picture-card"
    >
      <template slot="file" slot-scope="{file}">
        <!--<img class="el-upload-list__item-thumbnail" :attr="file.loading?'loading':''" :src="getFileText(file)" alt="">-->
        <div class="image" :style="`background-image:url(${getFileText(file)})`" :attr="file.loading?'loading':''"></div>
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePreview(file)"><i class="el-icon-zoom-in"></i></span>
          <span class="el-upload-list__item-delete"  @click="handleRemove(file)"><i class="el-icon-delete"></i></span>
        </span>
      </template>
      <el-button class="upload-img-icon" icon="el-icon-plus" circle  :loading="opt.loading"></el-button>
      <div slot="tip" class="el-upload__tip" v-show="Boolean(opt.showTips)">{{opt.showTips}}</div>
    </el-upload>
  </el-form-item>
</template>

<script>
  import extend from '../extend';

  const defaultOpt = {
    loading:false,
    showTips:"",
    showFile:true,
    name:'',
    text:'',
    className:'',
    fileSize:3, // M
    limit:1,
    multiple:true,
    buttonText:"上传文件",
    params:{path:"img"},
    props:{
      accept:'',
      disabled:false
    }
  }

  export default {
    name: "FormUpload",
    mixins:[extend],
    data(){
      return {
        showFile:false,
        classNames:['upload-img'],
        fileList:[],
        opt:{...defaultOpt}
      }
    },
    created(){
      this.nextUpload = _.debounce(nextUpload.bind(this),300)
    },
    mounted(){
      //this.initData();
    },
    methods: {
      setOpt(conf) {
        _.assign(this.opt, conf);
        this.showFile = this.opt.showFile;
        this.setValue(conf.value);
      },
      setValue(list) {
        let res = this.setValueMap(list);
        this.fileList = res;
        this.$forceUpdate();
      },
      setValueMap(list = []){
        if(Object.prototype.toString.call(list) == "[object String]"){
          list = [{name:list.replace(/.*\/(.*)/,'$1'),url:list}]
        }
        //
        if(this.column.limit == 1){
          this.data[this.opt.name] = list.length<1 ? '' : list[0]?.url;
        }else{
          this.data[this.opt.name] = list;
        }
        console.log("this.opt?.limit",this.opt?.limit)
        this.classNames.splice(0,1,(list?.length<this.opt?.limit) ?'':'limit-disabled')
        return list;
      },
      getFileText(file){
        let typeArr = ['txt','doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx','pdf'];
        let type = file.url.replace(/.*\.(.*)/,'$1');
        if(file.loading){
          return "/images/loading.gif"
        }
        return typeArr.indexOf(type)>-1 ? "/images/file.jpg" : file.url;
      },
      handleBefore(file){
        let opt = this.opt;
        let isOk = file.size / 1024 / 1024 < opt.fileSize;
        if(file.size<1){
          this.$message.warning(`上传文件过小！`);
          return false;
        }else if (!isOk) {
          this.$message.warning(`上传文件大小不能超过${opt.fileSize}MB!`);
        }
        return isOk;
      },
      handleRemove(file) {
        let idx = _.findIndex(this.fileList, file);
        this.fileList.splice(idx, 1);
        this.setValueMap(this.fileList);
      },
      handlePreview:(file)=>{
        //console.log(file);
        window.open(file.url);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 ${this.opt.limit}个文件`);
      },
      upload({file}) {
        let onUpload = this.opt.onUpload;
        const blob = new Blob([file], {type: file.type});
        const row = {name: file.name, url: '',file:file,loading:true};
        //const fileUrl = window.URL.createObjectURL(blob);
        this.fileList.push(row);
        this.setValueMap(this.fileList);
        if("flowUpload" === onUpload){
          this.nextUpload();
        }else{
          upload.call(this,row)
        }
      },
    }
  }


  // 上传
  function upload(row,callback = ()=>{}){
    let file = row.file;
    let params = {file,...this.opt.params};
    let ajaxPro = typeof this.opt.onUpload == 'function'? this.opt.onUpload(params):this.api("base.upload",params);
    row.file = void 0;
    row.ajax = true;
    row.loading = true;
    ajaxPro.then((res)=>{
      let data = res;
      row.name = file.name;
      row.url = data.url;
      row.originPath = data.url;
      row.smallUrl = data.smallUrl;
      row.id = data.imgId;
      row.yzImgId = data.yzImgId;
      row.imgType = params.imgTypeEnum;
    }).finally(()=>{
      this.fileList.splice(0,0)
      this.setValueMap(this.fileList);
      row.loading = false;
      row.ajax = false;
      callback(row);
    })
  }

  // 因为后端无法排序：只能顺序上传
  function nextUpload(){
    let sc = this;
    let exec = function(i){
      let fileList = sc.fileList;
      let row = fileList[i];
      if(!row || row.ajax){
        return;
      }
      // 执行下一个
      if(row.file){
        upload.call(sc,row,()=>{
          exec(i+1)
        })
      }else{
        exec(i+1)
      }
    }
    //
    exec(0)
  }
</script>

<style lang="scss">
.upload-img-icon{
  border:none;
  background:none;

  &:hover{
    background:none;
  }

  &:focus{
    background:none;
  }
}

.limit-disabled{
  .el-upload--picture-card{
    display:none;
  }
}
</style>
